<template>
  <div>
    <!-- 头部 -->
    <div class="table_header flex flex_bet" style="padding: 20px 20px 0 20px">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addButton">添加</el-button>
        <el-button type="primary" icon="el-icon-delete-solid" size="mini" @click.stop="getdeleteApp()">删除</el-button>
      </div>
      <div class="table_search flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="归属" value="1"></el-option>
              <el-option label="应用名称" value="2"></el-option>
              <el-option label="应用包名" value="3"></el-option>
              <!-- <el-option label="批次" value="4"></el-option> -->
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <el-button size="mini" type="primary" @click="cutLayout" style="margin-left:5px" class="iconfont" :class="layoutShow ? 'iconliebiaozhanshi' : 'iconshitugonggeListBox'"></el-button>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <div class="center" :class="layoutShow ? 'appCenter' : ''" style="padding-top: 0">

      <!-- 应用上传管理table -->
      <div>
        <!-- 内容start -->
        <div class="app" v-if="layoutShow">
          <ul>
            <li v-for="item in uploadingTable" :key="item.app_id" @click.stop="getqueryIdApp(item.app_id)">
              <div class="flex flex_bet felx_align">
                <div class="apply">{{item.app_name}}</div>
                <div style="margin-right:15px">
                  <el-button size="mini" icon="el-icon-delete" circle @click.stop="getdeleteApp(item.app_id)"></el-button>
                </div>
              </div>
              <div class="introduce flex felx_align flex_spa">
                <div class="app_img"><img :src="item.app_img" alt=""></div>
                <div class="category">
                  <div class="text">应用包名: {{item.app_package}}</div>
                  <div class="text">应用大小: {{item.app_size| zhDate}}</div>
                  <div class="text">推荐星星: <el-rate :value="Number(item.app_score)" disabled></el-rate>
                  </div>
                  <div class="text">版本号: {{item.app_version_name}}</div>
                  <div class="text">上传时间: {{item.app_createtime| newDate}}</div>
                  <div class="text">强制下载: <el-switch style="margin-left:5px" :value="!Boolean(item.app_forceinstall)" active-color="#409EFF" inactive-color="#dcdcdc" disabled></el-switch>
                  </div>
                  <div class="text">下载次数: {{item.app_downloads}}</div>
                  <div class="text">部署批次: {{item.app_batch}}</div>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <!-- 内容end -->
        <el-table stripe :data="uploadingTable" style="width: 100%" :key="key" border ref="tableDataRef" @selection-change="handleSelectionChange" @row-dblclick="tabCurrentChange" v-else>
          <el-table-column type="selection"></el-table-column>
          <el-table-column v-if="colData[0].istrue" prop="app_name" label="应用名称"  align="center" ></el-table-column>
          <el-table-column v-if="colData[1].istrue" prop="app_img" label="应用图标"  align="center">
            <template slot-scope="scope">
              <div class="icon_img flex flex_cen">
                <img :src="scope.row.app_img" alt />
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="colData[2].istrue" prop="app_attribution" label="归属"  align="center">
            <template slot-scope="scope">{{scope.row.username}}</template>
          </el-table-column>
          <el-table-column v-if="colData[3].istrue" prop="app_batch" label="批次"  align="center">
            <template slot-scope="scope">{{scope.row.app_batch == 0 ? '' : scope.row.app_batch}}</template>
          </el-table-column>
          <el-table-column v-if="colData[4].istrue" prop="app_createtime" label="上传时间"  align="center" sortable>
            <template slot-scope="scope">{{scope.row.app_createtime| newDate}}</template>
          </el-table-column>
          <el-table-column v-if="colData[5].istrue" prop="app_forceinstall" label="强制安装"  align="center">
            <template slot-scope="scope">
              <div>{{scope.row.app_forceinstall == 1 ? '否': '是'}}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="colData[6].istrue" prop="app_attribution" label="归属类型"  align="center">
            <template slot-scope="scope">
              <div>{{scope.row.app_attribution == 1 ? '专属': '公共'}}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="colData[7].istrue" prop="app_package" label="应用包名"  align="center"></el-table-column>
          <el-table-column v-if="colData[8].istrue" prop="app_version_name" label="版本号"  align="center"></el-table-column>
          <el-table-column v-if="colData[9].istrue" prop="app_version_code" label="内部版本号"  align="center"></el-table-column>
          <el-table-column v-if="colData[10].istrue" prop="app_size" label="应用大小"  align="center" sortable>
            <template slot-scope="scope">{{scope.row.app_size| zhDate}}</template>
          </el-table-column>
          <el-table-column v-if="colData[11].istrue" prop="app_downloads" label="下载次数"  align="center" sortable></el-table-column>
          <div v-if="!forbid">
            <el-table-column v-if="colData[12].istrue" prop="app_url" label="下载地址" align="center">
              <template slot-scope="scope">
                <div class="flex flex_cen">
                  <i class="iconfont iconanzhuo download" style="border:none;background-color:inherit;color:#a4c872">
                    <a target="_blank" :href="scope.row.app_url"></a>
                  </i>
                </div>
              </template>
            </el-table-column>
          </div>
          <el-table-column v-if="colData[13].istrue" prop="app_score" label="应用评分"  align="center"></el-table-column>
          <el-table-column v-if="colData[14].istrue" prop="app_desc" label="应用描述" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column v-if="colData[15].istrue" prop="app_developer" label="开发者（公司）"  align="center"></el-table-column>
          <el-table-column v-if="colData[16].istrue" prop="app_category_id" label="应用分类"  align="center">
            <template slot-scope="scope">{{scope.row.app_category_id == 0 ? '无' : scope.row.app_category_id}}</template>
          </el-table-column>
          <el-table-column v-if="colData[17].istrue" prop="app_brand_id" label="应用品牌"  align="center">
            <template slot-scope="scope">{{scope.row.app_brand_id == 0 ? '无' : scope.row.app_brand_id}}</template>
          </el-table-column>
          <el-table-column v-if="colData[18].istrue" prop="app_subject_id" label="应用专题"  align="center">
            <template slot-scope="scope">{{scope.row.app_subject_id == 0 ? '无' : scope.row.app_subject_id}}</template>
          </el-table-column>
          <!-- table编辑与操作 -->
          <el-table-column label="操作"  align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click.stop="getqueryIdApp(scope.row.app_id)">编辑</el-button>
              <el-button size="mini" @click.stop="getdeleteApp(scope.row.app_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="paging">
        <el-pagination :current-page.sync="listQuery.startSize" :page-sizes="[12, 60, 120, 240]" :page-size="12" layout="total, sizes, prev, pager, next, jumper" :total="total" background @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
      <!-- 隐藏部分 -->
      <!-- 添加 -->
      <el-dialog title="应用信息" :visible.sync="addFormVisible" width="60%" @close="addFormclose" top="5vh" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form :model="addForm" ref="numberValidateForm" :rules="rules" style="max-height: 625px; overflow: auto;">
          <el-form-item label="应用上传" label-width="120px">
            <el-upload class="upload-demo" :action="`${uploadLink}api/apkAdmin`" :data="pdfData" :show-file-list="false" :on-progress="replaceAvatarUpload" :on-success="handleSuccess" name="apk">
              <el-button size="small" type="primary"><span v-if="!apkSize">apk上传</span><span v-else>已上传( 文件{{apkSize | zhDate}} )</span></el-button>
              <el-progress :percentage="videoUploadPercent" v-if="!videoFlag" style="margin-top:10px"></el-progress>
            </el-upload>
          </el-form-item>
          <div class="flex">
            <el-form-item label="应用名称" label-width="120px" class="addform_headers" prop="appName">
              <el-input v-model="addForm.appName" autocomplete="off" class="add_select" placeholder="自动生成，请勿手动修改"></el-input>
            </el-form-item>
            <el-form-item label="应用包名" label-width="120px" class="addform_headers" prop="pakName">
              <el-input v-model="addForm.pakName" autocomplete="off" class="add_select" placeholder="自动生成，请勿手动修改"></el-input>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="版本号" label-width="120px" class="addform_headers" prop="versionName">
              <el-input v-model="addForm.versionName" autocomplete="off" class="add_select" placeholder="自动生成，请勿手动修改"></el-input>
            </el-form-item>
            <el-form-item label="内部版本号" label-width="120px" class="addform_headers" prop="versionCode">
              <el-input v-model="addForm.versionCode" controls-position="right" class="add_select" placeholder="自动生成，请勿手动修改"></el-input>
            </el-form-item>
          </div>
          <div class="flex flex_bet">
            <el-form-item label="应用图标" label-width="120px" class="addform_headers">
              <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="iconAvatarSuccess">
                <div v-if="addForm.imgPath" style="height:148px;width:148px">
                  <img :src="addForm.imgPath" class="avatar" style="height:100%;width:100%" />
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon" style="height:148px;width:148px;line-height: 148px;background-color: #fbfdff;"></i>
              </el-upload>
              <div style="line-height:0;color:red">*若系统自动生成不正确请手动上传</div>
            </el-form-item>
            <el-form-item label="应用图片" label-width="120px" class="addform_headers">
              <el-upload action="#" list-type="picture-card" :file-list="addForm.file" multiple :limit="3" :on-remove="handleRemove" :on-exceed="yHandleExceed" :http-request="handleAvatarSuccess">
                <div style="position:relative">
                  <i class="el-icon-plus"></i>
                  <p style="width:100%;position: absolute;top:25px;font-size:12px;color:#8c939d">建议分辨率：225x400</p>
                </div>

              </el-upload>
              <div style="line-height:30px;color:red">*请至少上传一张应用介绍图</div>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="应用品牌" label-width="120px" class="addform_headers" prop="pptype">
              <div class="flex felx_align">
                <el-radio-group v-model="addForm.pptype" style="width:28%" @change="brandclassifySelect" :disabled="lotdisabled">
                  <el-radio :label="0">无</el-radio>
                  <el-radio :label="1">有</el-radio>
                </el-radio-group>
                <el-select v-model="addForm.brandClassify" placeholder="请选择应用品牌" style="flex:1" :disabled="branddisabled" multiple>
                  <el-option v-for="item in brandoptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="应用类型" label-width="120px" prop="type">
              <el-radio-group v-model="addForm.type" style="width:100%" @change="lotclassifySelect">
                <el-radio :label="0">公共应用</el-radio>
                <el-radio :label="1">专属应用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="应用分类" label-width="120px" class="addform_headers" prop="yytype">
              <div class="flex felx_align">
                <el-radio-group v-model="addForm.yytype" style="width:28%" @change="classifySelect" :disabled="lotdisabled">
                  <el-radio :label="0">无</el-radio>
                  <el-radio :label="1">有</el-radio>
                </el-radio-group>
                <el-select v-model="addForm.classify" placeholder="请选择应用分类" style="flex:1" :disabled="typedisabled" multiple>
                  <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="强制安装" label-width="120px" prop="install">
              <el-switch v-model="addForm.install" active-color="#13ce66" inactive-color="#dcdcdc" :disabled="installDisabled"></el-switch>
              <span style="margin-left: 10px">{{addForm.install ? '是' : '否'}}</span><span style="color:red;margin-left:20px">(公共应用不允许强制安装)</span>
            </el-form-item>

          </div>
          <div class="flex">
            <div class="addform_headers">
              <el-form-item label="应用专题" label-width="120px" prop="zttype">
                <div class="flex felx_align">
                  <el-radio-group v-model="addForm.zttype" style="width:28%" @change="subjectclassifySelect" :disabled="lotdisabled">
                    <el-radio :label="0">无</el-radio>
                    <el-radio :label="1">有</el-radio>
                  </el-radio-group>
                  <el-select v-model="addForm.subjectClassify" placeholder="请选择应用专题" style="flex:1" :disabled="subjectdisabled" multiple>
                    <el-option v-for="item in subjectoptions" :key="item.name" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="开发者" label-width="120px" prop="app_developer">
                <el-input v-model="addForm.app_developer" autocomplete="off" class="add_select" placeholder="请输入开发者"></el-input>
              </el-form-item>
            </div>
            <div class="addform_headers">
              <el-form-item label="选择批次" label-width="120px" prop="lotClassify">
                <div class="flex">
                  <el-select v-model="addForm.lotClassify" :multiple-limit="10" placeholder="专属应用请选择批次" :disabled="lotdisabled" filterable multiple style="flex:1">
                    <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="应用初始评分值" label-width="120px">
                <div style="height:40px" class="flex felx_align">
                  <el-rate v-model="addForm.app_score"></el-rate>
                </div>
              </el-form-item>
            </div>
          </div>
          <el-form-item label="应用简介" label-width="120px" prop="app_desc">
            <el-input maxlength="150" show-word-limit autocomplete="off" placeholder="请输入应用简介,150字以内" type="textarea" v-model="addForm.app_desc" :rows="2"></el-input>
          </el-form-item>
          <h5 style="margin:0 0 0 60px;color:red">事项:</h5>
          <p style="margin:5px 0 0 60px;font-size: 14px">
            如果您上传的是第三方应用，<br>
            建议通过教管壹【管控部署】—【应用管控】下的【应用内部网页跳转管控】及【应用内部广告管控】功能进行封闭式管控，<br>
            并在【应用自启/升级/联网】管控功能中设置为禁止升级，以免该应用可能存在的广告插件上网及其他网页跳转上网等；
          </p>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addFormVisible = false" size="mini" round>取 消</el-button>
          <Debounce>
            <el-button v-if="apkUnplate" type="primary" @click.native="geteditApp('numberValidateForm')" size="mini" round>确 定</el-button>
            <el-button v-else type="primary" @click.native="addApk" size="mini" round>apk上传</el-button>
          </Debounce>
        </div>
      </el-dialog>
      <!-- 删除弹窗 -->
      <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @shutDialogs="shutDialogs" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
    </div>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { apkAdmin, queryAppAll, queryIdApp, uploadPreviewImg, queryCategory, queryBrand, querySubject, editApp, addApp, deleteApp, queryUserIdCategory, queryUserIdBrand, queryUserIdSubject } from "@/api/application";
import { getBatchTwo } from "@/api/equipment.js";
import deleteDialog from "@/components/deleteDialog";
import forbid from '@/directive/permission/forbid.js'
import readMachine from 'app-info-parser'
import jszip from 'jszip'
import axios from 'axios'
import BMF from 'browser-md5-file'
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      apkFiles: '',
      checkboxVal: ["应用名称", "应用图标", "归属", "批次", "上传时间", "强制安装", "归属类型", "应用包名", "版本号", "内部版本号",
        "应用大小", "下载次数", "下载地址", "应用评分", "应用描述", "开发者（公司）", "应用分类", "应用品牌", "应用专题"],
      key: 1,
      colData: [], //动态控制table
      uploadingTable: [],
      //添加表单
      addForm: {
        appName: "", pakName: "", versionName: "", versionCode: "",
        imgPath: "", //左侧多选select
        idSelect: [],
        file: [],//应用图片
        install: false,//强制安装
        app_developer: '',
        classify: '',//应用分类
        brandClassify: '',//品牌分类
        subjectClassify: '',//专题分类
        lotClassify: '',//批次分类
        type: 0, yytype: 0, pptype: 0, zttype: 0,
        app_desc: '',//应用简介
        bg: '',
        app_score: 4//打分
      },
      rules: {},
      value: "",
      //控制添加表单显示
      addFormVisible: false,
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      images: "",
      //控制拖拽kpi上传
      apkVisible: false,
      total: 0, //总数量
      searchTable: "", //
      select: "", //搜索条件
      arr: [],
      //应用分类下来选择
      options: [],
      //应用品牌下拉选择
      brandoptions: [],
      //专题下拉选择
      subjectoptions: [],
      //批次下拉选择
      lotoptions: [],
      //分类应用是否禁用多选
      typedisabled: true,
      //分类品牌是否禁用多选
      branddisabled: true,
      //专题禁用多选
      subjectdisabled: true,
      //批次禁用多选
      lotdisabled: true,
      //上传后台获取的数据
      app: [],
      //编辑应用后台获取的数据
      complieApp: [],
      //apk上传按钮控制
      apkUnplate: true,
      //进度条
      videoUploadPercent: 0,
      videoFlag: true,
      pdfData: { userId: '', last_ip: '' },
      installDisabled: true,
      listQuery: { startSize: 1, pageSize: 12, userId: localStorage.getItem("ID"), app_name: undefined, app_package: undefined, username: undefined, app_batch: undefined },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      //APK上传大小
      apkSize: 0,
      layoutShow: false,
      forbid: Boolean,
      uploadLink: process.env.VUE_APP_BASE_API
    };
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryAppAll();
    this.pdfData.userId = localStorage.getItem("ID")
    this.pdfData.last_ip = sessionStorage.getItem("Ip")
    this.forbid = forbid(['超级管理员', '管理员'])
    console.log('权限', this.uploadLink)
  },
  methods: {
    cutLayout() {
      this.layoutShow = !this.layoutShow
    },
    addButton() {
      this.apkUnplate = false
      this.addFormVisible = true
    },
    //关闭删除弹窗
    shutDialogs() {
      this.deleteDialogs.show = false
    },
    //删除
    getdeleteApp(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      if (!this.deleteDialogs.deleteId) {
        this.deleteDialogs.deleteId = this.idSelect[0].app_id
      }
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        app_id: this.deleteDialogs.deleteId
      }
      deleteApp(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryAppAll()
      }).catch(err => {
        console.log("请求失败", err)
      })
    },
    //更换安装包
    replaceAvatarUpload(event, file, fileList) {
      this.videoFlag = false;
      this.videoUploadPercent = Math.floor(event.percent)
    },
    handleSuccess(res) {
      console.log('上传APK返回的信息', res)
      if (res.code == 200) {
        this.getqueryUserIdCategory()
        this.getqueryUserIdBrand()
        this.getqueryUserIdSubject()
        this.getBatchTwos()
        this.addFormVisible = true;
        this.videoFlag = true
        this.addForm.pakName = res.data.pakName;
        this.addForm.versionName = res.data.versionName;
        this.addForm.versionCode = res.data.versionCode;
        this.addForm.imgPath = res.data.imgPath;
        this.addForm.appName = res.data.appName;
        this.app = res.data;
        this.apkVisible = false;
        this.addForm.bg = res.data.bg
        this.apkSize = res.data.size
      } else {
        this.$message.error(res.msg)
        this.videoFlag = true
      }
    },
    //编辑应用管理
    getqueryIdApp(app_id) {
      //console.log('重复打开',this.addForm.file)
      let that = this
      that.addFormVisible = true
      that.apkUnplate = true
      queryIdApp({ app_id: app_id }).then(res => {
        //上传成功后后台返回apk相应的信息并展示
        let data = res.data[0]
        that.app = data
        that.complieApp = data
        that.addForm.pakName = data.app_package;
        that.addForm.versionName = data.app_version_name;
        that.addForm.versionCode = data.app_version_code;
        that.addForm.imgPath = data.app_img;
        that.addForm.appName = data.app_name;
        that.addForm.app_developer = data.app_developer
        that.addForm.app_desc = data.app_desc
        //that.addForm.file = [{ url: data.app_preview1 }, { url: data.app_preview2 }, { url: data.app_preview3 }]
        //只有一张图片的话图片回显就会出现三张，一一判断
        data.app_preview1 != null ? that.addForm.file.push({ url: data.app_preview1 }) : ''
        data.app_preview2 != null ? that.addForm.file.push({ url: data.app_preview2 }) : ''
        data.app_preview3 != null ? that.addForm.file.push({ url: data.app_preview3 }) : ''
        that.addForm.install = !Boolean(data.app_forceinstall)//1代表否，0代表强制安装
        that.apkSize = data.app_size
        that.addForm.bg = data.bg
        that.addForm.app_score = Number(data.app_score)
        console.log('最初的数据', data)
        //为0表示单选选的0，不为0表示选了多项传过来的是数组
        if (data.app_category_id != '0') {
          that.addForm.yytype = 1
          that.typedisabled = false
          data.app_category_id != null ? that.addForm.classify = data.app_category_id.split(',').map(item => Number(item)) : ''
        } else {
          that.addForm.yytype = 0
        }
        if (data.app_brand_id != '0') {
          that.addForm.pptype = 1
          that.branddisabled = false
          data.app_brand_id != null ? that.addForm.brandClassify = data.app_brand_id.split(',').map(item => Number(item)) : ''
        } else {
          that.addForm.pptype = 0
        }
        if (data.app_subject_id != '0') {
          that.addForm.zttype = 1
          that.subjectdisabled = false
          data.app_subject_id != null ? that.addForm.subjectClassify = data.app_subject_id.split(',').map(item => Number(item)) : ''
        } else {
          that.addForm.zttype = 0
        }
        if (data.app_attribution != '0') {
          that.addForm.type = 1
          this.installDisabled = false
          that.lotdisabled = false
          data.app_batch != null ? that.addForm.lotClassify = data.app_batch.split(',') : ''
        } else {
          that.addForm.type = 0
        }
      }).catch(err => {
        console.log("请求失败", err)
      })
      this.getqueryUserIdCategory()
      this.getqueryUserIdBrand()
      this.getqueryUserIdSubject()
      this.getBatchTwos()
    },
    //编辑应用按钮事件
    geteditApp() {
      if (this.addForm.type == 1) {//选完专属批次列表不能为空
        if (this.addForm.lotClassify == '') {
          return this.$message.error('请选择批次')
        }
      }
      //console.log('编辑apk', this.addForm)
      let data = {
        app_name: this.addForm.appName,
        app_package: this.addForm.pakName,
        //更换安装包后，后台返回的数据字段不一样，所：用 ||
        app_version_name: this.app.app_version_name || this.app.versionName,
        app_version_code: this.app.app_version_code || this.app.versionCode,
        app_size: this.app.app_size || this.app.size,
        app_desc: this.addForm.app_desc,
        app_url: this.app.app_url || this.app.filePath,
        app_img: this.addForm.imgPath,
        app_preview1: this.addForm.file[0] ? this.addForm.file[0].url : '',
        app_preview2: this.addForm.file[1] ? this.addForm.file[1].url : '',
        app_preview3: this.addForm.file[2] ? this.addForm.file[2].url : '',
        app_developer: this.addForm.app_developer,
        app_category_id: this.addForm.yytype == 0 ? this.addForm.yytype : this.addForm.classify.toString(),
        app_brand_id: this.addForm.pptype == 0 ? this.addForm.pptype : this.addForm.brandClassify.toString(),
        app_subject_id: this.addForm.zttype == 0 ? this.addForm.zttype : this.addForm.subjectClassify.toString(),
        app_attribution: this.addForm.type,
        app_batch: this.addForm.type == 0 ? 0 : this.addForm.lotClassify.toString(),
        app_id: this.complieApp.app_id,
        app_forceinstall: Number(!this.addForm.install),//1代表否，0代表强制安装
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        app_md5: this.app.md5 || this.app.app_md5,
        bg: this.addForm.bg,
        app_score: this.addForm.app_score
      }
      console.log('编辑apk', data)
      editApp(data).then(res => {
        this.$message.success(res.msg)
        this.addFormVisible = false
        this.getqueryAppAll()
      }).catch(err => {
        console.log("请求失败222", err)
      })
    },
    //上传应用按钮事件
    addApk() {
      if (this.addForm.type == 1) {//选完专属批次列表不能为空
        if (this.addForm.lotClassify == '') {
          return this.$message.error('请选择批次')
        }
      }
      let data = {
        app_name: this.addForm.appName,
        app_package: this.addForm.pakName,
        app_version_name: this.app.versionName,
        app_version_code: this.app.versionCode,
        app_size: this.app.size,
        app_desc: this.addForm.app_desc != '' ? this.addForm.app_desc : 0,
        app_url: this.app.filePath,
        app_img: this.addForm.imgPath,
        app_preview1: this.addForm.file[0] ? this.addForm.file[0].url : '',
        app_preview2: this.addForm.file[1] ? this.addForm.file[1].url : '',
        app_preview3: this.addForm.file[2] ? this.addForm.file[2].url : '',
        app_developer: this.addForm.app_developer != '' ? this.addForm.app_developer : 0,
        app_category_id: this.addForm.yytype == 0 ? this.addForm.yytype : this.addForm.classify.toString(),
        app_brand_id: this.addForm.pptype == 0 ? this.addForm.pptype : this.addForm.brandClassify.toString(),
        app_subject_id: this.addForm.zttype == 0 ? this.addForm.zttype : this.addForm.subjectClassify.toString(),
        app_attribution: this.addForm.type,
        app_batch: this.addForm.type == 0 ? 0 : this.addForm.lotClassify.toString(),
        app_admin_id: localStorage.getItem("ID"),
        app_forceinstall: Number(!this.addForm.install),//1代表否，0代表强制安装
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        app_md5: this.app.md5,
        bg: this.addForm.bg,
        app_score: this.addForm.app_score
      }
      console.log('上传apk的参数', data)
      addApp(data).then(res => {
        this.$message.success(res.msg)
        this.addFormVisible = false
        this.getqueryAppAll();
      }).catch(err => {
        console.log("请求失败333", err);
      })
    },
    //图片上传时的钩子
    handleAvatarSuccess(item) {
      //this.arr.push(res.raw)
      let fd = new FormData();
      fd.append('file', item.file)
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('userId', localStorage.getItem("ID"))
      // this.arr.forEach(function (file) {
      //   fd.append('file', file); // 因为要上传多个文件，所以需要遍历一下才行,不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      //   console.log('-----------',file)
      // })
      console.log('------自定义上传', item.file)
      uploadPreviewImg(fd).then(res => {
        //多张上传会返回null。
        if (res.data.imgPath != null) {
          this.addForm.file.push({ url: res.data.imgPath })
        }
        //console.log("push过后的数据", res);
        this.arr = [];
      }).catch(err => {
        this.arr = []
      })
    },
    //应用图标上传时的钩子
    iconAvatarSuccess(res, file) {
      //console.log('......', res, file)
      let fd = new FormData();
      fd.append('file', res.raw);
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('userId', localStorage.getItem("ID"))
      uploadPreviewImg(fd).then(res => {
        this.addForm.imgPath = res.data.imgPath
      }).catch(err => {
        console.log("请求失败22", err);
      })
    },
    handleRemove(file, fileList) {
      //console.log('删除removu', file, fileList);
      this.addForm.file = fileList
    },
    yHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，如想上传请先删除图片`);
    },
    //添加上传apk
    apkAvatarUpload(file) {
      // this.apkUnplate = false;//将添加和上传的按钮分开
      // var fd = new FormData();
      // fd.append("userId", this.$store.state.user.token);
      // fd.append("last_ip", localStorage.getItem("Ip"));
      // fd.append("apk", file.raw);
      // this.getApk(fd)
    },
    //编辑apk上传
    compileapkAvatarUpload(file) {
      var fd = new FormData();
      fd.append("userId", this.$store.state.user.token);
      fd.append("last_ip", sessionStorage.getItem("Ip"));
      fd.append("apk", file.raw);
      this.getApk(fd)
    },
    //apk接口上传
    getApk(fd) {
      apkAdmin(fd).then(res => {
        //上传成功后后台返回apk相应的信息并展示
        this.addForm.pakName = res.data.pakName;
        this.addForm.versionName = res.data.versionName;
        this.addForm.versionCode = res.data.versionCode;
        this.addForm.imgPath = res.data.imgPath;
        this.addForm.appName = res.data.appName;
        this.app = res.data;
        this.apkVisible = false;
        this.addFormVisible = true;
        //debugger;
      }).catch(err => {
        console.log("请求失败", err);
      });
      this.getqueryUserIdCategory()
      this.getqueryUserIdBrand()
      this.getqueryUserIdSubject()
      this.getBatchTwos()
    },
    //获取应用信息
    getqueryAppAll(startSize = 1, pageSize = 10, type = 1, parameter) {
      queryAppAll(this.listQuery).then(res => {
        this.uploadingTable = res.data;
        this.total = res.total;
        console.log('--------', res.data)
      }).catch(err => {
        this.uploadingTable = []
        this.total = 0
      });
    },
    //搜索,1:id,2,应用名称，3应用包名，4归属,5批次
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.username = this.searchTable
          this.getqueryAppAll();
          break;
        case '2':
          this.listQuery.app_name = this.searchTable
          this.getqueryAppAll();
          break;
        case '3':
          this.listQuery.app_package = this.searchTable
          this.getqueryAppAll();
          break;
        case '4':
          this.listQuery.app_batch = this.searchTable
          this.getqueryAppAll();
          break;
      }
    },

    //根据ID获取应用分类
    getqueryUserIdCategory() {
      queryUserIdCategory({ userId: localStorage.getItem("ID") }).then(res => {
        this.options = res.data
      }).catch(err => {
        this.options = []
        // console.log("根据ID获取应用分类 请求失败", err)
      })
    },
    //根据ID获取应用品牌列表
    getqueryUserIdBrand() {
      queryUserIdBrand({ userId: localStorage.getItem("ID") }).then(res => {
        this.brandoptions = res.data
      }).catch(err => {
        this.brandoptions = []
        console.log("根据ID获取应用品牌列表 请求失败", err)
      })
    },
    //根据ID获取专题列表
    getqueryUserIdSubject() {
      queryUserIdSubject({ userId: localStorage.getItem("ID") }).then(res => {
        this.subjectoptions = res.data
        console.log('获取应用专题', res.data)
      }).catch(err => {
        this.subjectoptions = []
        console.log('获取应用专题', err)
        //console.log("根据ID获取专题列表请求失败", err)
      })
    },
    //根据ID获取批次列表
    getBatchTwos() {
      //console.log('出发了')
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
        //console.log("根据ID获取批次列表请求失败", err)
      })
    },
    //表格多选事件
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.tableDataRef.clearSelection()
        this.$refs.tableDataRef.toggleRowSelection(val.pop())
      } else {
        this.idSelect = val
      }
      console.log("表格多选事件", this.idSelect)
    },
    tabCurrentChange(row) {
      this.getqueryIdApp(row.app_id)
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.numberValidateForm.resetFields();
        this.addForm = {
          appName: "",
          pakName: "",
          versionName: "",
          versionCode: "",
          imgPath: "",
          file: [],//应用图片
          install: false,//强制安装
          app_developer: '',
          classify: '',//应用分类
          brandClassify: '',//品牌分类
          subjectClassify: '',//专题分类
          lotClassify: '',//批次分类
          type: 0,
          yytype: 0,
          pptype: 0,
          zttype: 0,
          app_desc: '',//应用简介
          bg: '',
          app_score: 4
        },
          this.installDisabled = true,
          this.videoFlag = true,
          this.lotdisabled = true,//批次禁用
          this.branddisabled = true,//分类品牌是否禁用多选
          this.typedisabled = true,//分类应用是否禁用多选
          this.subjectdisabled = true//专题禁用多选
        this.apkSize = 0
      })
    },
    //应用分类下拉菜单事件
    classifySelect(val) {
      if (val == 0) {
        this.typedisabled = true
      } else {
        this.typedisabled = false
      }
    },
    //应用品牌下拉菜单事件
    brandclassifySelect(val) {
      if (val == 0) {
        this.branddisabled = true
      } else {
        this.branddisabled = false
      }
    },
    //应用专题下拉菜单事件
    subjectclassifySelect(val) {
      if (val == 0) {
        this.subjectdisabled = true
      } else {
        this.subjectdisabled = false
      }
    },
    //应用专题下拉菜单事件
    //监听应用类型，选择公共应用后强制安装不能开启
    lotclassifySelect(val) {
      if (val == 0) {
        this.lotdisabled = true
        this.installDisabled = true
        this.addForm.install = false
        this.addForm.lotClassify = ''
        this.addForm.pptype = 0
        this.addForm.brandClassify = ''
        this.addForm.yytype = 0
        this.branddisabled = true
        this.typedisabled = true
        this.subjectdisabled = true
        this.addForm.classify = ''
        this.addForm.zttype = 0
        this.addForm.subjectClassify = ''
      } else {
        this.lotdisabled = false
        this.installDisabled = false
        //this.addForm.install = true
      }
    },
    //分页
    handleSizeChange(val) {
      //console.log("每页多少天", val);
      this.listQuery.pageSize = val
      this.getqueryAppAll();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAppAll();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 12, userId: localStorage.getItem("ID"), app_name: undefined, app_package: undefined, username: undefined, app_batch: undefined }
      this.getqueryAppAll()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
  }
};
</script>

<style scoped>
/deep/ thead .el-table-column--selection .cell {
  display: none;
}
</style>

<style lang="scss" scoped>
.el-textarea__inner {
  height: 150px !important;
}
.addform_headers {
  width: 50%;
}
.picture_rm {
  margin: 10px 0;
  .rm_btn {
    width: 100px !important;
    margin-top: 10px;
  }
}
.icons_img {
  height: 100px;
  width: 100px;
  img {
    height: 100%;
    width: 100%;
  }
}
.icon_select {
  width: 77.5%;
  float: left;
}

.download {
  display: inline-block;
  height: 30px;
  width: 30px;
  line-height: 30px;
  box-shadow: none;
  border-left: 0;
  border-radius: 2px;
  position: relative;
  a {
    position: absolute;
    top: 0;
    left: 0;
    display: inline-block;
    height: 30px;
    width: 30px;
  }
}
.site_inputs {
  box-shadow: none;
  border-color: #666666;
  border: 1px solid #ccc;
  border-radius: 2px;
  padding: 5px 10px;
  color: #666666;
}
.app {
  ul {
    display: flex;
    flex-wrap: wrap;

    li {
      background-color: #fff;
      border-radius: 19px;
      padding: 15px 0;
      width: 23%;
      margin: 20px 15.5px 0 15.5px;
      .apply {
        margin-left: 15px;
        font-weight: 600;
        color: #333333;
        overflow: hidden;
        width: 60%;
        text-overflow: ellipsis;
        white-space: nowrop;
      }
      .introduce {
        margin-top: 10px;
        font-size: 12px;
        color: #333333;
        .app_img {
          width: 70px;
          height: 70px;
          // border: 1px solid #b9b8b8;
          overflow: hidden;
          border-radius: 13px;
          img {
            height: 100%;
            width: 100%;
          }
        }
        .app_icon {
          font-size: 28px;
          margin-bottom: 25px;
        }
        .category {
          max-width: 60%;
          .text {
            line-height: 18px;
            word-wrap: break-word;
            word-break: normal;
          }
        }
      }
    }
  }
}
.appCenter {
  min-height: calc(100vh - 50px);
  width: 100%;
  background-color: #ebebeb;
}
.apkButton {
  position: relative;
  #file {
    opacity: 0;
    height: 28px;
    width: 77px;
  }
  .apkBtn {
  }
}
</style>

<style>
.el-list-leave-active {
  transition: none;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
</style>
